package by.home.controller;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.StringTokenizer;

import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator;

public class ActionManager {

    protected ClassFinder classFinder;
    static private final Logger log = Logger.getLogger(ActionManager.class);

    public ActionManager(ClassFinder classFinder) {
        DOMConfigurator.configure("log4j.xml");
        this.classFinder = classFinder;
    }

    public Action getActionByPageName(String page) {
        Action action = null;
        String pageName = getRequestPageByName(page);
        Class actionClass = classFinder.getActionClass(pageName);
        try {
            Constructor constructor = actionClass.getConstructor();
            action = (Action) constructor.newInstance();
        } catch (Exception e) {
            log.error(e);
            return null;
        }
        return action;
    }


    private String getRequestPageByName(String page) {
        StringTokenizer stringTokenizer = new StringTokenizer(page, "/");
        String requestPage = "";
        while (stringTokenizer.hasMoreTokens()) {
            requestPage = stringTokenizer.nextToken();
        }
        return requestPage;
    }

}
